package com.md.api.service.impl;

import com.md.api.common.utils.TokenUtil;
import com.md.api.dao.TbOrderMapper;
import com.md.api.dao.VipPropertiesMapper;
import com.md.api.entity.HttpResult;
import com.md.api.entity.TbOrder;
import com.md.api.entity.TbOrderDetail;
import com.md.api.entity.dto.ComposeCommitDto;
import com.md.api.entity.dto.ComposeQueryDto;
import com.md.api.entity.enums.PayStatus;
import com.md.api.entity.util.Page;
import com.md.api.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Author liujie
 * @ClassName VipCenterServiceImpl
 **/

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {


    @Resource
    VipPropertiesMapper vipMapper;
    @Resource
    TbOrderMapper orderMapper;
    @Resource
    TokenUtil tokenUtil;

    @Override
    public HttpResult myOrder(HttpServletRequest request, ComposeQueryDto qto) {
        Page page = qto.getPage();
        page.initPagingData(TbOrder.class);
        String userId = tokenUtil.getUserId(request);
        List<TbOrder> list = orderMapper.list(userId,qto.getPayStatus(),qto.getOrderType(),qto.getPayType(),qto.getPayTimeStart(),qto.getPayTimeEnd());
        page.setResult(list);
        return new HttpResult(page);
    }


    @Override
    public HttpResult confirmOrder(HttpServletRequest request, ComposeQueryDto qto) {
        String userId = tokenUtil.getUserId(request);
        TbOrder byOrderNo = orderMapper.getByOrderNo(qto.getOrderNo());
        if (byOrderNo.getUserId().equals(userId)) {
            orderMapper.confirmOrder(qto.getOrderNo(),qto.getSkuId(),1);
            //该订单下的所有产品都确认收货了，订单完成
            int count = orderMapper.getNotConfirmOrderCount(qto.getOrderNo());
            if (count==0) {
                byOrderNo.setPayStatus(PayStatus.COMPLETED.value());
                orderMapper.updateOrder(byOrderNo);
            }
        }
        return HttpResult.OK;
    }

    @Override
    public HttpResult deleteOrder(HttpServletRequest request, ComposeCommitDto qto) {
        String userId = tokenUtil.getUserId(request);
        TbOrder dbOrder = orderMapper.getByOrderNo(qto.getOrderNo());
        if (dbOrder.getUserId().equals(userId)){
            orderMapper.deleteByOrderNo(qto.getOrderNo());
        }else {
            return HttpResult.fail("該訂單不屬於您！");
        }

        return HttpResult.OK;
    }

    @Override
    public HttpResult orderDetail(HttpServletRequest request, ComposeCommitDto qto) {
        TbOrder dbOrder = orderMapper.getByOrderNo(qto.getOrderNo());
        List<TbOrderDetail> details = orderMapper.orderDetail(qto.getOrderNo());
        if (!CollectionUtils.isEmpty(details)){
            dbOrder.setDetailList(details);
        }
        return new HttpResult(dbOrder);
    }
}
